(function () {
    var exports = this;
    var $ = null;

    var Mahjang_ZongJiesuanLayer = cc.Layer.extendEX({
        /**
         * 复制分享文本
         */
        _infoText: '',
        /**
         * 总结算数据
         */
        _data: null,
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
        },
        onExit: function () {
            cc.Layer.prototype.onExit.call(this);
            $ = null;
        },
        ctor: function (data) {
            var self = this;
            self._super();
            self._data = data;
      
            loadNodeCCS(majiang.res.ZongJiesuanLayer_json, self);
            $ = create$(this.getChildByName('Node'));
            self._setRoomId();
            self._setPlayers();
            self._setRowPos();
            self._setInfoText();
            self._setBtnEvent();
            return true;
        },
        /**
         * 设置房间号/局数/玩法描述
         */
        _setRoomId: function () {
            var self = this;
            $("root.txtRoomId").setString('房号：' + gameData.roomId);
            $("root.txtRounds").setString('局数：' + self._data['cur_round'] + '/' + self._data['total_round']);
            $("root.txtRoomInfo").setString(gameData.wanfaDesp);
            if (self._data.club_id && !isNaN(parseInt(self._data.club_id)) && parseInt(self._data.club_id) > 0){
                $('root.flag_qinyouquan').setVisible(true);
                loadHeadImage(self._data.club_info.club_head, $('root.flag_qinyouquan.head'), true);
                $('root.flag_qinyouquan.clubName').setString(self._data.club_info.club_name);
                //$('root.flag_qinyouquan.clubID').setString(self._data.club_id);
            }
            else {
                $('root.flag_qinyouquan').setVisible(false);
            }
        },
        /**
         * 设置时间
         * @private
         */
        _setTime: function () {
            var self = this;
            var time = self._data['EndTime'].split(' ');
            $("root.lb_ts").setString(time[0]+'\n'+time[1]);
        },
        /**
         * 设置玩家数据
         * @private
         */
        _setPlayers: function () {
            var self = this;
            self.maxDianpao = 0;
            self.maxScore = 0;
            self.maxUid = 0;
            var players = self._data['players'];
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                if (self.maxScore < player['score']) {
                    self.maxScore = player['score'];
                }
            }
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var uid = player['uid'];
                var score = player['score'];
                var playerInfo = gameData.getPlayerInfoByUid(uid);
                self.fenshu = self.fenshu + playerInfo.nickname + ":" + score + "\n";
                self._setRowUnit(i, player);
            }
            for (; i < 4; i++) {
                var RowUnit = $("root.rowWidth.row" + i);
                if (RowUnit) {
                    RowUnit.setVisible(false);
                }
            }
        },
        /**
         * 设置玩家显示位置
         * @private
         */
        _setRowPos: function () {
            var self = this;
            var count = 1100;
            var midpoint = 0;
            if ($('root.rowWidth')) {
                count = $('root.rowWidth').getContentSize().width;
                midpoint = $('root.rowWidth').getPositionX();
            }
            var players = self._data['Users'] || self._data['players'];
            var interval = count / players.length;
            var width = $('root.rowWidth.row1').getPositionX() - $('root.rowWidth.row0').getPositionX();
            if (players.length == 2) {
                interval = (count - 2 * width) / 3 + width
            }
            var originPosX = midpoint - (players.length - 1) / 2 * interval - width / 2;
            for (var s = 0; s < players.length; s++) {
                $('root.rowWidth.row' + s).setPositionX(originPosX + interval * s);
            }
        },
        /**
         * 设置分享文本
         * @private
         */
        _setInfoText: function () {
            var self = this;
            this._infoText = "";
            var map_id = self._data['Map_id'] || self._data['map_id'];
            var wanfa = (map_id ? ('玩法：' + gameData.mapId2Name(map_id)) : '玩法：');
            var endTime = "结束时间：" + timestamp2time(self._data['ts']);
            var dyjName = "大赢家:";
            var count = 0;
            for (var i = 0; i < self._data['players'].length; i++) {
                var player = self._data['players'][i];
                if(self.maxScore>0 && player['score'] == self.maxScore){
                    var playerInfo = gameData.getPlayerInfoByUid(player['uid']);
                    dyjName += count>0?(','+playerInfo['nickname']):playerInfo['nickname'];
                    count++;
                }
            }
            this._infoText = this._infoText + wanfa + "\n" + endTime + "\n" + self.fenshu + (count>0?dyjName:"");
        },
        /**
         * 设置玩家牌数据
         * @param index
         * @param player
         * @private
         */
        _setRowUnit: function (index, player) {
            var self = this;
            var uid = player['UserID'] || player['uid'];
            var playerInfo = gameData.getPlayerInfoByUid(uid);
            self._setRowHead(index, playerInfo);
            self._setRowState(index, player);
            self._setScore(index, player);
            self._setScroll(index, player);
            self._setFangzhu(index, player);
        },
        /**
         * 设置玩家头像
         * @param index
         * @param playerInfo
         * @private
         */
        _setRowHead: function (index, playerInfo) {
            var self = this;
            var RowUnit = $("root.rowWidth.row" + index);
            $("txtName", RowUnit).setString(ellipsisStr(playerInfo['nickname'], 6));
            $("txtID", RowUnit).setString("ID:" + playerInfo['uid']);
            var oriUrl = gameData.getUserInfo(playerInfo['uid'])['headimgurl'];
            var url = decodeURIComponent(oriUrl || playerInfo['headimgurl']);
            loadHeadImage(url, RowUnit.getChildByName('head') , true);//头像
        },
        /**
         * 设置状态
         * @param index
         * @param playerData
         * @private
         */
        _setRowState: function (index, playerData) {
            var self = this;
            var RowUnit = $("root.rowWidth.row" + index);
            var score = playerData['Score'] || playerData['score'];
            $("dyj", RowUnit).setVisible(self.maxScore <= score && score > 0);
            $("tuhao", RowUnit).setVisible(false);
        },
        /**
         * 设置分数
         * @param index
         * @param playerData
         * @private
         */
        _setScore: function (index, playerData) {
            var self = this;
            var RowUnit = $("root.rowWidth.row" + index);
            var score = playerData['Score'] || playerData['score'];
            $("lb_score_win", RowUnit).setString(score);
            $("lb_score_fail", RowUnit).setString(score);
            $("lb_score_win", RowUnit).setVisible(score >= 0);
            $("lb_score_fail", RowUnit).setVisible(score < 0);
            $("shu_bg", RowUnit).setVisible(score < 0);
            $("ying_bg", RowUnit).setVisible(score >= 0);
        },
        /**
         * 设置列表
         * @param index
         * @param playerData
         * @private
         */
        _setScroll: function (index, playerData) {
            var self = this;
            var RowUnit = $("root.rowWidth.row" + index);
            var sv = $("sv", RowUnit);
            var row0 = $("row0", sv);
            var Scores = playerData['Scores'] || playerData['scores'];
            row0.setVisible(false);
            var totalheight = row0.getContentSize().height * Scores.length;
            if (totalheight < sv.getContentSize().height)
                totalheight = sv.getContentSize().height;
            sv.setInnerContainerSize(cc.size(sv.getContentSize().width, totalheight));
            for (var j = 1; j <= Scores.length; j++) {
                var row = $("row" + j, RowUnit);
                if (!row) {
                    row = duplicateNode(row0);
                    row.setName('row' + j);
                    sv.addChild(row);
                }
                row.setVisible(true);
                row.setPosition(0, totalheight - j * row0.getContentSize().height);

                row.getChildByName("txt_jushu").setString('第' + j + '局');
                var _score = Scores[j-1];
                _score = _score >= 0 ? ('+' + _score) : _score;
                row.getChildByName("txt_score").setString(_score);

                row.getChildByName("txt_jushu").setLocalZOrder(2);
                row.getChildByName("txt_score").setLocalZOrder(2);
            }
        },
        /**
         * 设置玩家房主
         * @param index
         * @param playerInfo
         * @private
         */
        _setFangzhu: function (index,playerInfo) {
            var self = this;
            var RowUnit = $("root.rowWidth.row" + index);
            $("fz", RowUnit).setVisible(false);
        },
        /**
         * 设置按钮事件
         * @private
         */
        _setBtnEvent: function () {
            var self = this;
            TouchUtil.setOnclickListener($('root.btn_return'), function () {
                showBoard('HallBoard');
            });
            $('root.btn_xianliao').setVisible(false);
            $('root.btn_fenxianglianjie').setVisible(false);
            TouchUtil.setOnclickListener($('root.btn_xianliao'), function () {
            });
            TouchUtil.setOnclickListener($('root.btn_weixin'), function () {
                WeChatUtil.shareCapture(self);
            });
            TouchUtil.setOnclickListener($('root.btn_fenxianglianjie'), function () {
            });
            TouchUtil.setOnclickListener($('root.btn_cpyInfo'), function () {
                self._clickCpyInfo();
            });
        },
        _clickCpyInfo: function () {
            var self = this;
            var clubName = self._data.club_info.club_name == '' ? '' : (self._data.club_info.club_name + '\n');
            var jushu = '(' + self._data.cur_round + '/' + self._data.total_round + ')';
            var jiesuanTitle = ' 总结算 ';
            var roomId = '房间号：' + self._data.room_id + '\n';
            var playerinfo = '';
            for (var i = 0; i < self._data.players.length; i++) {
                var tmpInfo = self._data.players[i];
                var tmpName = gameData.getPlayerInfoByUid(tmpInfo['uid'])['nickname'];
                var score = tmpInfo.score;
                playerinfo += (tmpName + ' : ' + score + '\n');
            }

            var wanfaDesp = gameData.wanfaDesp;

            var cpyInfo = clubName + jushu + jiesuanTitle + roomId + playerinfo + wanfaDesp;
            console.log(cpyInfo);
            DeviceUtil.savePasteBoard(cpyInfo);
            showToast('复制成功');
        }
    });

    exports.Mahjang_ZongJiesuanLayer = Mahjang_ZongJiesuanLayer;
})(window);
